const {
  calculateBMI,
  getBMIStatus,
  calculateBMR,
  calculateDailyIntake,
  generateMealRecommendations,
  generateNutritionTips,
} = require("../../utils/mealRecommendation");
import recommendedMeals from "../../data/meals";

Page({
  data: {
    loading: true,
    hasUserInfo: false,
    userInfo: {
      name: "",
      gender: "1",
      age: "",
      height: "",
      weight: "",
      activityLevelId: "",
      dietPreferenceId: "",
    },
    activityLevels: [
      { id: 1, name: "久坐不动" },
      { id: 2, name: "轻度活动" },
      { id: 3, name: "中度活动" },
      { id: 4, name: "重度活动" },
      { id: 5, name: "极重度活动" },
    ],
    dietPreferences: [
      { id: 1, name: "标准饮食" },
      { id: 2, name: "减重" },
      { id: 3, name: "增重" },
      { id: 4, name: "素食" },
      { id: 5, name: "无特殊偏好" },
    ],
    activityIndex: 0,
    dietIndex: 0,
    healthData: {},
    bmiStatus: {},
    dailyIntake: {},
    nutritionGoals: {
      calories: 0,
      protein: 0,
      carbs: 0,
      fat: 0,
    },
    recommendedMeals,
    nutritionTips: [],
    currentDate: "",
    _scrollRetries: 0,
  },

  onLoad() {
    // 设置当前日期
    this.setCurrentDate();

    // 初始化选择器索引
    this.setData({
      activityIndex: 0,
      dietIndex: 0,
      "userInfo.activityLevelId": Number(this.data.activityLevels[0].id),
      "userInfo.dietPreferenceId": Number(this.data.dietPreferences[0].id)
    });
    
    // 获取用户健康数据
    this.getUserHealthData();
  },

  onShow() {
    // 刷新用户健康数据，获取最新的数据库信息
    this.getUserHealthData();
    
    // 检查是否有特定的功能跳转
    this.checkFeatureNavigation();
  },

  // 检查是否有特定的功能跳转
  checkFeatureNavigation() {
    // 从全局变量获取目标区域
    const app = getApp();
    if (app.globalData && app.globalData.targetSection) {
      const targetSection = app.globalData.targetSection;
      console.log('检测到目标区域:', targetSection);
      
      // 防止重复跳转，添加时间戳检查
      const now = Date.now();
      const lastScrollTime = app.globalData.lastScrollTime || 0;
      
      // 如果距离上次跳转不到1秒，则不再执行跳转
      if (now - lastScrollTime < 1000) {
        console.log('检测到短时间内重复跳转，已忽略');
        app.globalData.targetSection = null;
        return;
      }
      
      // 记录本次跳转时间
      app.globalData.lastScrollTime = now;
      
      // 滚动到指定区域
      this.scrollToSection(targetSection);
      
      // 使用后清除，避免影响下次显示
      app.globalData.targetSection = null;
    }
  },
  
  // 滚动到指定区域的函数
  scrollToSection(sectionId) {
    console.log('准备滚动到区域:', sectionId);
    
    // 确保页面已加载完成再执行滚动
    if (this.data.loading) {
      console.log('页面加载中，延迟滚动');
      // 如果页面仍在加载，等待加载完成后再滚动
      setTimeout(() => {
        this.scrollToSection(sectionId);
      }, 500);
      return;
    }
    
    // 使用延时确保DOM已完全渲染
    setTimeout(() => {
      const query = wx.createSelectorQuery();
      query.select('#' + sectionId)
        .boundingClientRect(rect => {
          if (rect) {
            console.log('找到目标区域，位置信息:', rect);
            
            // 添加小偏移量，确保区域完全可见
            const scrollTop = rect.top - 10;
            
            wx.pageScrollTo({
              scrollTop: scrollTop > 0 ? scrollTop : 0, // 确保不会有负值
              duration: 300,
              success: () => console.log('成功滚动到指定区域'),
              fail: (err) => console.error('滚动失败:', err)
            });
          } else {
            console.error('未找到目标区域:', sectionId);
            // 目标区域未找到，可能需要多次尝试
            if (!this._scrollRetries) {
              this._scrollRetries = 1;
            } else {
              this._scrollRetries++;
            }
            
            // 最多尝试3次
            if (this._scrollRetries <= 3) {
              console.log(`尝试再次查找区域(${this._scrollRetries}/3)...`);
              setTimeout(() => {
                this.scrollToSection(sectionId);
              }, 300);
            } else {
              console.log('已达到最大重试次数，放弃滚动');
              this._scrollRetries = 0;
            }
          }
        })
        .exec();
    }, 500);
  },

  // 显示饮食记录相关内容
  showDietRecords() {
    console.log("显示饮食记录内容");
    this.scrollToSection('health-overview');
  },

  // 显示营养方案相关内容
  showNutritionPlan() {
    console.log("显示营养方案内容");
    this.scrollToSection('meal-recommendations');
  },

  // 显示健康分析相关内容
  showHealthAnalysis() {
    console.log("显示健康分析内容");
    this.scrollToSection('nutrition-tips');
  },

  // 设置当前日期
  setCurrentDate() {
    const now = new Date();
    const year = now.getFullYear();
    const month = String(now.getMonth() + 1).padStart(2, "0");
    const day = String(now.getDate()).padStart(2, "0");
    this.setData({
      currentDate: `${year}-${month}-${day}`,
    });
  },

  // 获取用户健康数据
  async getUserHealthData() {
    try {
      console.log("开始获取用户健康数据...");
      
      // 首先尝试从云函数获取健康数据
      const { result } = await wx.cloud.callFunction({
        name: "quickstartFunctions",
        data: {
          type: "getUserHealthData",
        },
      });

      console.log("云函数返回结果:", JSON.stringify(result));
      
      // 尝试从getUserInfo接口获取用户基本信息
      if (result.code === 404 || !result.data) {
        console.log("未找到健康数据，尝试从用户信息中获取...");
        
        try {
          const res = await wx.cloud.callFunction({
            name: "quickstartFunctions",
            data: {
              type: "getUserInfo",
              data: {
                refresh: true,
              }
            },
          });
          
          console.log("获取用户信息结果:", JSON.stringify(res.result));
          
          if (res.result.code === 200 && res.result.data && res.result.data.wechatUserDto) {
            const wechatUserDto = res.result.data.wechatUserDto;
            console.log("从wechatUserDto中获取用户数据:", JSON.stringify(wechatUserDto));
            
            // 检查wechatUserDto中是否包含必要的健康信息
            if (wechatUserDto.height && wechatUserDto.weight && 
                wechatUserDto.age && wechatUserDto.gender && 
                wechatUserDto.activityLevelId && wechatUserDto.dietPreferenceId) {
                
              // 构建用户健康数据
              const userData = {
                name: wechatUserDto.name || wechatUserDto.nickName || "",
                gender: String(wechatUserDto.gender),
                age: Number(wechatUserDto.age),
                height: Number(wechatUserDto.height),
                weight: Number(wechatUserDto.weight),
                activityLevelId: Number(wechatUserDto.activityLevelId),
                dietPreferenceId: Number(wechatUserDto.dietPreferenceId)
              };
              
              console.log("从用户信息构建的健康数据:", JSON.stringify(userData));
              
              // 计算选择器的索引位置
              const activityIndex = this.data.activityLevels.findIndex(
                (level) => level.id === userData.activityLevelId
              );
              
              const dietIndex = this.data.dietPreferences.findIndex(
                (pref) => pref.id === userData.dietPreferenceId
              );
              
              console.log("计算的索引 - 活动:", activityIndex, "饮食:", dietIndex);
              
              this.setData({
                hasUserInfo: true,
                userInfo: userData,
                activityIndex: activityIndex >= 0 ? activityIndex : 0,
                dietIndex: dietIndex >= 0 ? dietIndex : 0,
              });
              
              // 计算健康指标
              this.calculateHealthMetrics(userData);
              return;
            } else {
              console.log("wechatUserDto中缺少必要的健康信息字段");
            }
          }
        } catch (error) {
          console.error("获取用户信息失败:", error);
        }
        
        // 如果以上尝试都失败，则显示填写表单
        console.log("未能从其他接口获取健康数据，显示信息填写界面");
        this.setData({
          hasUserInfo: false,
          loading: false,
        });
        return;
      }

      if (result.code === 200 && result.data) {
        const userData = result.data;
        console.log("获取到用户数据:", JSON.stringify(userData));
        
        // 确保关键字段为正确的类型
        const processedUserData = {
          ...userData,
          activityLevelId: Number(userData.activityLevelId),
          dietPreferenceId: Number(userData.dietPreferenceId),
          age: Number(userData.age),
          height: Number(userData.height),
          weight: Number(userData.weight),
          gender: String(userData.gender)
        };
        
        console.log("处理后的用户数据:", JSON.stringify(processedUserData));
        
        // 计算选择器的索引位置
        const activityIndex = this.data.activityLevels.findIndex(
          (level) => level.id === processedUserData.activityLevelId
        );
        
        const dietIndex = this.data.dietPreferences.findIndex(
          (pref) => pref.id === processedUserData.dietPreferenceId
        );
        
        console.log("计算的索引 - 活动:", activityIndex, "饮食:", dietIndex);
        
        this.setData({
          hasUserInfo: true,
          userInfo: processedUserData,
          activityIndex: activityIndex >= 0 ? activityIndex : 0,
          dietIndex: dietIndex >= 0 ? dietIndex : 0,
        });

        // 计算健康指标
        this.calculateHealthMetrics(processedUserData);
      } else {
        console.log("未获取到有效用户数据，显示信息填写界面");
        this.setData({
          hasUserInfo: false,
          loading: false,
        });
      }
    } catch (error) {
      console.error("获取用户健康数据失败:", error);
      wx.showToast({
        title: "获取数据失败",
        icon: "none",
      });
      this.setData({
        loading: false,
      });
    }
  },

  // 计算健康指标
  calculateHealthMetrics(userData) {
    const { weight, height, age, gender, activityLevelId, dietPreferenceId } =
      userData;

    // 计算BMI
    const bmi = calculateBMI(weight, height);
    const bmiStatus = getBMIStatus(bmi);

    // 计算基础代谢率
    const bmr = calculateBMR(weight, height, age, gender);

    // 计算每日推荐摄入量
    const dailyIntake = calculateDailyIntake(
      bmr,
      activityLevelId,
      dietPreferenceId
    );

    // 生成早餐推荐
    const recommendedBreakfast = this.generatePersonalizedBreakfast(
      bmi,
      dailyIntake,
      dietPreferenceId,
      activityLevelId,
      age
    );

    // 生成营养建议
    const nutritionTips = generateNutritionTips(
      bmi,
      dietPreferenceId,
      activityLevelId
    );

    this.setData({
      healthData: {
        ...userData,
        bmi,
      },
      bmiStatus,
      dailyIntake,
      recommendedMeals: {
        breakfast: recommendedBreakfast
      },
      nutritionTips,
      loading: false,
    });
  },

  // 生成个性化早餐推荐
  generatePersonalizedBreakfast(bmi, dailyIntake, dietPreferenceId, activityLevelId, age) {
    const breakfastCalories = Math.round(dailyIntake.calories * 0.3); // 早餐占总热量的30%
    const breakfastProtein = Math.round(dailyIntake.protein * 0.3); // 早餐蛋白质也占30%
    
    let breakfastOptions = [];
    
    if (bmi < 18.5) {
      // 偏瘦人群推荐高能量、高蛋白的早餐
      breakfastOptions = [
        {
          id: 'recipe-1001',
          name: '能量全谷物早餐',
          image: '/images/meals/breakfast1.png',
          description: '富含优质蛋白和复合碳水化合物，帮助健康增重',
          calories: Math.round(breakfastCalories * 1.1),
          nutrition: { protein: Math.round(breakfastProtein * 1.2) },
          price: 28
        },
        {
          id: 'recipe-1002',
          name: '牛奶燕麦果仁碗',
          image: '/images/meals/breakfast2.png',
          description: '添加坚果和水果的高能量早餐，促进营养吸收',
          calories: breakfastCalories,
          nutrition: { protein: breakfastProtein },
          price: 25
        }
      ];
    } else if (bmi >= 25) {
      // 超重人群推荐低热量、高饱腹感的早餐
      breakfastOptions = [
        {
          id: 'recipe-1003',
          name: '轻食蔬果早餐',
          image: '/images/meals/breakfast3.png',
          description: '低热量高纤维，饱腹不长胖',
          calories: Math.round(breakfastCalories * 0.8),
          nutrition: { protein: breakfastProtein },
          price: 22
        },
        {
          id: 'recipe-1004',
          name: '蛋白质能量碗',
          image: '/images/meals/breakfast1.png',
          description: '富含优质蛋白，促进新陈代谢',
          calories: Math.round(breakfastCalories * 0.9),
          nutrition: { protein: Math.round(breakfastProtein * 1.1) },
          price: 26
        }
      ];
    } else {
      // 正常体重人群推荐均衡营养的早餐
      breakfastOptions = [
        {
          id: 'recipe-1005',
          name: '均衡营养早餐',
          image: '/images/meals/breakfast2.png',
          description: '营养均衡，维持健康体重',
          calories: breakfastCalories,
          nutrition: { protein: breakfastProtein },
          price: 24
        },
        {
          id: 'recipe-1006',
          name: '活力三明治套餐',
          image: '/images/meals/breakfast3.png',
          description: '美味可口，营养均衡的早餐组合',
          calories: breakfastCalories,
          nutrition: { protein: breakfastProtein },
          price: 23
        }
      ];
    }

    // 根据活动水平调整推荐
    if (activityLevelId >= 4) {
      // 重度活动人群额外推荐
      breakfastOptions.push({
        id: 'recipe-1007',
        name: '运动能量早餐',
        image: '/images/meals/breakfast1.png',
        description: '高能量高蛋白，为运动提供充足能量',
        calories: Math.round(breakfastCalories * 1.2),
        nutrition: { protein: Math.round(breakfastProtein * 1.3) },
        price: 30
      });
    }

    // 根据年龄调整推荐
    if (age >= 50) {
      // 中老年人群额外推荐
      breakfastOptions.push({
        id: 'recipe-1008',
        name: '养生早餐',
        image: '/images/meals/breakfast2.png',
        description: '易消化吸收，营养丰富均衡',
        calories: Math.round(breakfastCalories * 0.9),
        nutrition: { protein: breakfastProtein },
        price: 26
      });
    }

    return breakfastOptions;
  },

  // 处理输入变化
  handleInput(e) {
    const { field } = e.currentTarget.dataset;
    const value = e.detail.value;
    this.setData({
      [`userInfo.${field}`]: value,
    });
  },

  // 处理性别选择
  handleGenderChange(e) {
    this.setData({
      "userInfo.gender": e.detail.value,
    });
  },

  // 处理活动水平选择
  handleActivityChange(e) {
    const index = e.detail.value;
    const activityId = this.data.activityLevels[index].id;
    console.log("设置活动水平ID:", activityId, "类型:", typeof activityId);
    this.setData({
      activityIndex: index,
      "userInfo.activityLevelId": Number(activityId),
    });
  },

  // 处理饮食偏好选择
  handleDietChange(e) {
    const index = e.detail.value;
    const dietId = this.data.dietPreferences[index].id;
    console.log("设置饮食偏好ID:", dietId, "类型:", typeof dietId);
    this.setData({
      dietIndex: index,
      "userInfo.dietPreferenceId": Number(dietId),
    });
  },

  // 提交用户信息
  async submitUserInfo() {
    const userInfo = this.data.userInfo;
    console.log("提交前检查用户信息:", JSON.stringify(userInfo));

    // 验证必填字段
    const requiredFields = [
      "name",
      "gender",
      "age",
      "height",
      "weight",
      "activityLevelId",
      "dietPreferenceId",
    ];
    
    // 更严格的验证
    const missingFields = requiredFields.filter((field) => {
      const value = userInfo[field];
      const isEmpty = value === undefined || value === null || value === "";
      if (isEmpty) {
        console.log(`字段 ${field} 为空, 值:`, value);
      }
      return isEmpty;
    });

    if (missingFields.length > 0) {
      console.log("缺少必填字段:", missingFields);
      wx.showToast({
        title: "请填写完整信息",
        icon: "none",
      });
      return;
    }

    // 强制转换字段类型
    const formattedUserInfo = {
      name: userInfo.name,
      gender: String(userInfo.gender),
      age: Number(userInfo.age),
      height: Number(userInfo.height),
      weight: Number(userInfo.weight),
      activityLevelId: Number(userInfo.activityLevelId),
      dietPreferenceId: Number(userInfo.dietPreferenceId),
    };

    console.log("准备提交的用户信息:", formattedUserInfo);
    console.log("活动水平ID类型:", typeof formattedUserInfo.activityLevelId, "值:", formattedUserInfo.activityLevelId);
    console.log("饮食偏好ID类型:", typeof formattedUserInfo.dietPreferenceId, "值:", formattedUserInfo.dietPreferenceId);

    try {
      // 调用云函数更新用户信息
      const { result } = await wx.cloud.callFunction({
        name: "quickstartFunctions",
        data: {
          type: "updateUserInfo",
          data: {
            userInfo: formattedUserInfo,
          },
        },
      });

      console.log("云函数返回结果:", result);

      if (result.code === 200) {
        // 更新本地数据
        this.setData({
          userInfo: {
            ...this.data.userInfo,
            ...formattedUserInfo,
          },
          hasUserInfo: true,
        });

        // 计算健康指标
        this.calculateHealthMetrics(formattedUserInfo);

        wx.showToast({
          title: "保存成功",
          icon: "success",
        });
      } else {
        throw new Error(result.msg || "保存失败");
      }
    } catch (error) {
      console.error("保存用户信息失败:", error);
      wx.showToast({
        title: error.message || "保存失败",
        icon: "none",
        duration: 2000,
      });
    }
  },

  // 更新用户信息
  updateUserInfo() {
    this.setData({
      hasUserInfo: false,
    });
  },

  // 调整方案
  adjustPlan() {
    // 实现调整方案的逻辑
    wx.showToast({
      title: "功能开发中",
      icon: "none",
    });
  },

  // 跳转到添加饮食记录页面
  navigateToAddMeal() {
    // 模拟添加饮食记录
    const currentCalories = this.data.nutritionGoals.calories || 0;
    const currentProtein = this.data.nutritionGoals.protein || 0;

    // 模拟增加300卡路里和10g蛋白质
    const newCalories = Math.min(
      currentCalories + 300,
      this.data.dailyIntake.calories
    );
    const newProtein = Math.min(
      currentProtein + 10,
      this.data.dailyIntake.protein
    );

    this.setData({
      "nutritionGoals.calories": newCalories,
      "nutritionGoals.protein": newProtein,
    });

    // 显示添加成功提示
    wx.showToast({
      title: "记录成功",
      icon: "success",
    });
  },

  // 点击了解更多
  viewTipDetail: function (event) {
    const tip = event.currentTarget.dataset.tip;
    // 将对象转换为查询字符串参数
    const params = encodeURIComponent(JSON.stringify(tip));
    wx.navigateTo({
      url: `/pages/nutrition-extra/tip-detail/index?tip=${params}`,
    });
  },

  // 查看餐品详情
  viewMealDetail(e) {
    const id = e.currentTarget.dataset.id;
    console.log('查看餐品详情，餐品ID:', id);
    
    // 获取当前餐品信息
    const mealList = this.data.recommendedMeals.breakfast;
    const currentMeal = mealList.find(item => item.id === id);
    
    if (!currentMeal) {
      console.error('未找到餐品信息');
      wx.showToast({
        title: '餐品信息不存在',
        icon: 'none'
      });
      return;
    }
    
    console.log('当前餐品信息:', currentMeal);
    
    // 确保ID格式正确，统一格式为recipe-开头
    let recipeId = id;
    if (!id.startsWith('recipe-')) {
      recipeId = `recipe-${id}`;
    }
    
    // 提取数字ID部分
    const numericId = recipeId.replace('recipe-', '');
    
    // 构建详情页参数，包含餐品价格信息
    const params = `id=${numericId}&price=${currentMeal.price}&priceSource=nutrition`;
    
    // 首先尝试跳转到标准路径
    const url = `/pages/recipe/detail/index?${params}`;
    
    wx.navigateTo({
      url: url,
      success: () => {
        console.log('跳转到菜谱详情页成功');
      },
      fail: (err) => {
        console.error('标准路径跳转失败:', err);
        
        // 尝试备用路径
        const backupUrl = `/pages/discover/recipe/detail/index?${params}`;
        wx.navigateTo({
          url: backupUrl,
          success: () => {
            console.log('使用备用路径跳转成功');
          },
          fail: (err2) => {
            console.error('备用路径跳转也失败:', err2);
            wx.showToast({
              title: '无法打开详情页',
              icon: 'none'
            });
          }
        });
      }
    });
  },
  
  // 立即订购餐品
  orderMeal(e) {
    // 获取餐品ID
    const id = e.currentTarget.dataset.id;
    console.log('立即订购按钮被点击，餐品ID:', id);
    
    // 检查ID是否有效
    if (!id) {
      console.error('餐品ID无效');
      wx.showToast({
        title: '餐品信息不存在',
        icon: 'none'
      });
      return;
    }
    
    // 获取当前餐品信息
    const mealList = this.data.recommendedMeals.breakfast;
    const currentMeal = mealList.find(item => item.id === id);
    
    if (!currentMeal) {
      console.error('未找到餐品信息');
      wx.showToast({
        title: '餐品信息不存在',
        icon: 'none'
      });
      return;
    }
    
    console.log('当前餐品信息:', currentMeal);
    
    // 确保ID格式正确，统一格式为recipe-开头
    let recipeId = id;
    if (!id.startsWith('recipe-')) {
      recipeId = `recipe-${id}`;
    }
    
    // 提取数字ID部分
    const numericId = recipeId.replace('recipe-', '');
    
    // 构建详情页参数，包含餐品价格信息
    const params = `id=${numericId}&price=${currentMeal.price}&priceSource=nutrition`;
    
    // 直接跳转到菜谱详情页
    const url = `/pages/recipe/detail/index?${params}`;
    console.log('准备跳转到:', url);
    
    wx.navigateTo({
      url: url,
      success: () => {
        console.log('跳转成功');
      },
      fail: (err) => {
        console.error('跳转失败:', err);
        
        // 尝试使用备用路径
        const backupUrl = `/pages/discover/recipe/detail/index?${params}`;
        console.log('尝试使用备用路径:', backupUrl);
        
        wx.navigateTo({
          url: backupUrl,
          success: () => {
            console.log('使用备用路径跳转成功');
          },
          fail: (err2) => {
            console.error('备用路径跳转也失败:', err2);
            
            // 最后尝试通过switchTab先切换到发现页面
            wx.switchTab({
              url: '/pages/discover/index',
              success: () => {
                // 延迟执行第二次导航，确保先完成Tab切换
                setTimeout(() => {
                  console.log('延迟导航到菜谱详情页');
                  wx.navigateTo({
                    url: backupUrl,
                    fail: (err3) => {
                      console.error('三次导航都失败:', err3);
                      wx.showToast({
                        title: '无法打开菜谱详情',
                        icon: 'none'
                      });
                    }
                  });
                }, 300);
              },
              fail: (err2) => {
                console.error('切换Tab也失败:', err2);
                wx.showToast({
                  title: '页面跳转失败',
                  icon: 'none'
                });
              }
            });
          }
        });
      }
    });
  },
});
